package com.liuyucheng.concurrent.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreDemo {
    public static void main(String[] args) {
        // 创建一个最多允许 2 个线程同时执行的 Semaphore
        Semaphore semaphore = new Semaphore(2);

        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(5);

        // 提交 5 个任务，但最多只有 2 个能同时执行
        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            executor.execute(() -> {
                try {
                    // 获取许可
                    semaphore.acquire();
                    System.out.println("任务 " + taskId + " 开始执行（剩余许可：" + semaphore.availablePermits() + "）");

                    // 模拟任务执行
                    Thread.sleep(2000);

                    System.out.println("任务 " + taskId + " 执行完毕");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    // 释放许可
                    semaphore.release();
                }
            });
        }

        executor.shutdown();
    }
}